package com.wn.servlet.demo03;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author yellow Docter
 * @date 2022 -06-28
 * @desc
 *
 * 01 servletContext的作用
 *    1, 可以实现 servlet中的数据共享
 *    2. 可以搞全局配置
 *    3. 可以读取资源
 *
 * 02 如何获取servletContext : 每个web程序只能有一个,该对象的生命周期，跟Tomcat同步！
 *    01 调用父类的方法
 *       getServletContext()
 *    02 通过config对象来获取
 *       getServletConfig().getServletContext();
 *    03 通过session
 *       req.getSession().getServletContext();
 *
 *  03 多个servlet可以实现数据共享
 *      servletContext 内部有一个map 存储数据
 *       key    就是键    字符串
 *       value  就是值     Object
 *
 *       servletContext.setAttribute(key,value);  添加
 *       servletContext.getAttribute(key);        获取
 *       servletContext..removeAttribute(key);    移除
 *
 */
@WebServlet(urlPatterns = "/context01")
public class Context01Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext servletContext = getServletContext();
        ServletContext servletContext2 = getServletContext();

        System.out.println("servletContext = " + servletContext.hashCode());
        System.out.println("servletContext2 = " + servletContext2.hashCode());

        servletContext.setAttribute("key1","刘强东");
        servletContext.setAttribute("key2",30);
        servletContext.setAttribute("key3",new Date());

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
